package com.uzai.console.service.sms.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.RandomUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.login.Code;
import com.uzai.console.enums.SmsType;
import com.uzai.console.service.sms.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jianghan
 * @date 2019-04-03 14:16
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
    private String product = "Dysmsapi";
    private String domain = "dysmsapi.aliyuncs.com";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    @Override
    public void sms(String phone, Code code) {
        if (StringUtils.isBlank(phone) || phone.length()!=11){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MOBILE_ERROR);
        }

        if(code == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统异常");
        }
        Integer type = code.getType();
        if(code.getType() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入验证码类型参数");
        }

        SmsType smsType = SmsType.getValue(type);
        if(smsType == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "验证码类型参数不正确");
        }
        String code_random = RandomUtil.getSmsCode(4);
        if(type.intValue() <= 5) { //复制配置方案
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random, 5, TimeUnit.MINUTES);
        }else if(type.intValue() == 6){//个人微信通讯录wxid
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,5, TimeUnit.MINUTES);
        }else if(type.intValue() == 7){//个人微信会员wxid
            Long userId = code.getUserId();
            if(userId == null){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id参数");
            }
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone, userId), code_random,5, TimeUnit.MINUTES);
        }else if (type.intValue() == 8) {
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 9){
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 10){//好友请求wxid
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 11){//会员数据处理
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 12){//会员数据删除
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 13){//群成员显示wxid
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 14){//事件报警配置修改
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 15){//提现列表显示支付宝信息
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 17){//订单数据删除
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 18){//免单淘礼金显示
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 19){//显示会员mobile
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 20){//实名认证
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 21){//短信验证配置
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }else if(type.intValue() == 22){//修改会员余额积分
            redisTemplate.opsForValue().set(String.format(smsType.getDesc(), phone), code_random,60, TimeUnit.SECONDS);
        }
        //调用CMS发送短信接口，发送短信
        Map<String, Object> params = new HashMap<>();
        params.put("code", code_random);
        sms(smsType.getTempId(), phone, params);
    }

    private void sms(String tempId, String mobile, Object params) {
        try {
            String paramStr = Tools.getStrEmpty(JSONObject.toJSONString(params));
            logger.info("tempId is :{},mobile is :{},params is :{}", new Object[]{tempId,mobile,paramStr});
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", uzaiConsoleSysConfig.getAliyunAccessKeyId(), uzaiConsoleSysConfig.getAliyunAccessKeySecret());
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            //短信签名
            request.setSignName(uzaiConsoleSysConfig.getAliyunSmsTitle());
            //短信模板
            request.setTemplateCode(tempId);
            //模板中的变量替换JSON串
            request.setTemplateParam(paramStr);

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("sendSmsResponse:{},{},{}",new Object[]{sendSmsResponse.getRequestId(),sendSmsResponse.getCode(),sendSmsResponse.getMessage()});

            String respCode = sendSmsResponse.getCode();
            if ("isv.BUSINESS_LIMIT_CONTROL".equals(respCode)){
                throw new BusinessException("操作频率太快，请稍后再试!"+params);
            }
        } catch (ClientException e) {
            logger.error("sms error:{}",e);
        }
    }

    /**
     * 调用短信模板发送消息
     * @author jitwxs
     * @date 2023/8/14 16:20
     * @param tempId
     * @param mobile
     */
    public void smsTemplate(String tempId, String mobile) {
        try {
            logger.info("tempId is :{},mobile is :{}", new Object[]{tempId,mobile});
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", uzaiConsoleSysConfig.getAliyunAccessKeyId(), uzaiConsoleSysConfig.getAliyunAccessKeySecret());
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(mobile);
            //短信签名
            request.setSignName(uzaiConsoleSysConfig.getAliyunSmsTitle());
            //短信模板
            request.setTemplateCode(tempId);

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("sendSmsResponse:{},{},{}",new Object[]{sendSmsResponse.getRequestId(),sendSmsResponse.getCode(),sendSmsResponse.getMessage()});

            String respCode = sendSmsResponse.getCode();
            if ("isv.BUSINESS_LIMIT_CONTROL".equals(respCode)){
                throw new BusinessException("操作频率太快，请稍后再试!");
            }
        } catch (ClientException e) {
            logger.error("sms error:{}",e);
        }
    }
}